package com.yt.user.server.api.cms;

import com.yt.common.constant.Result;
import com.yt.user.models.dto.SysAdminDTO;
import com.yt.user.models.service.IUserSysAdminRemoteService;
import com.yt.common.utils.Md5Utils;
import com.yt.user.server.service.impl.SysAdminFallbackServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;

@RestController
@RequestMapping("/api/admin")
@Api(tags = "管理员重置密码接口")
public class AdminResetPasswordController {
    
    private static final Logger log = LoggerFactory.getLogger(AdminResetPasswordController.class);

    @DubboReference(check = false, timeout = 10000, retries = 0, interfaceClass = IUserSysAdminRemoteService.class, lazy = true)
    private IUserSysAdminRemoteService sysAdminRemoteService;
    
    @Autowired
    private SysAdminFallbackServiceImpl sysAdminFallbackService;
    
    @PostMapping(path = "/resetPassword", consumes = "application/json")
    @ApiOperation("管理员重置密码")
    public Result<String> resetPassword(@Valid @RequestBody ResetPasswordRequest resetPasswordRequest) {
        return processResetPassword(resetPasswordRequest);
    }
    
    // 支持表单数据的重载方法
    @PostMapping(path = "/resetPassword", consumes = "application/x-www-form-urlencoded")
    @ApiOperation("管理员重置密码(表单)")
    public Result<String> resetPasswordForm(
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String newPassword) {
        
        ResetPasswordRequest request = new ResetPasswordRequest();
        request.setUsername(username);
        request.setNewPassword(newPassword);
        
        return processResetPassword(request);
    }
    
    private Result<String> processResetPassword(ResetPasswordRequest resetPasswordRequest) {
        try {
            // 1. 参数校验
            if (resetPasswordRequest.getUsername() == null || resetPasswordRequest.getUsername().isEmpty() ||
                resetPasswordRequest.getNewPassword() == null || resetPasswordRequest.getNewPassword().isEmpty()) {
                return Result.fail("用户名或新密码不能为空");
            }
            
            // 2. 查询管理员信息
            SysAdminDTO admin = null;
            try {
                if (sysAdminRemoteService == null) {
                    log.error("sysAdminRemoteService is null, dubbo service not initialized properly. Please check if yt-sys-server is running and Zookeeper is available.");
                    // 使用本地回退实现
                    admin = sysAdminFallbackService.getByUsername(resetPasswordRequest.getUsername());
                    log.info("使用本地回退服务查询管理员信息");
                } else {
                    admin = sysAdminRemoteService.getByUsername(resetPasswordRequest.getUsername());
                }
            } catch (Exception e) {
                log.error("调用sysAdminRemoteService.getByUsername发生异常: ", e);
                // 出现异常时使用本地回退实现
                try {
                    admin = sysAdminFallbackService.getByUsername(resetPasswordRequest.getUsername());
                    log.info("远程服务调用异常，使用本地回退服务查询管理员信息");
                } catch (Exception fallbackException) {
                    log.error("本地回退服务调用也失败: ", fallbackException);
                    return Result.fail("系统服务异常，请稍后再试");
                }
            }
            
            if (admin == null) {
                return Result.fail("管理员不存在");
            }
            
            // 3. 重置密码
            try {
                boolean updateResult = false;
                if (sysAdminRemoteService == null) {
                    log.info("使用本地回退服务更新管理员密码");
                    updateResult = sysAdminFallbackService.updatePasswordByUsername(resetPasswordRequest.getUsername(), resetPasswordRequest.getNewPassword());
                } else {
                    try {
                        updateResult = sysAdminRemoteService.updatePasswordByUsername(resetPasswordRequest.getUsername(), resetPasswordRequest.getNewPassword());
                    } catch (Exception e) {
                        log.error("调用sysAdminRemoteService.updatePasswordByUsername发生异常: ", e);
                        // 出现异常时使用本地回退实现
                        updateResult = sysAdminFallbackService.updatePasswordByUsername(resetPasswordRequest.getUsername(), resetPasswordRequest.getNewPassword());
                        log.info("远程服务调用异常，使用本地回退服务更新管理员密码");
                    }
                }
                
                if (updateResult) {
                    return Result.success("密码重置成功");
                } else {
                    return Result.fail("密码更新失败");
                }
            } catch (Exception e) {
                log.error("更新密码发生异常: ", e);
                return Result.fail("密码更新失败: " + e.getMessage());
            }
        } catch (Exception e) {
            log.error("重置密码发生异常: ", e);
            return Result.fail("密码重置失败: " + e.getMessage());
        }
    }
    
    @Data
    public static class ResetPasswordRequest implements Serializable {
        private static final long serialVersionUID = 1L;

        @ApiModelProperty(value = "管理员用户名", required = true)
        @NotBlank(message = "用户名不能为空")
        private String username;
        
        @ApiModelProperty(value = "新密码", required = true)
        @NotBlank(message = "新密码不能为空")
        private String newPassword;
    }
}